﻿using Client.Constant;
using Client.Framework.Event;
using Client.Framework.Message;
using Client.Framework.Socket;
using Client.Message.Request;
using Client.Message.Response;
using Client.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Client.Service
{
    /// <summary>
    /// Author: Leil
    /// Description: 角色服务
    /// CreateTime: 2020/6/1 9:49:08
    /// </summary>
    public class RoleService
    {

        public delegate void RefreshRolesDelegate(List<ViewRole> roles);

        public event RefreshRolesDelegate RefreshRolesEvent;

        public void SubscribeRefreshRolesEvent(RefreshRolesDelegate refreshEvent)
        {
            RefreshRolesEvent += refreshEvent;
        }

        private static RoleService instance;

        private RoleService()
        {
            MessageEventPublisher.SubscribeEvent(MessageId.RESPONSE_ALL_ROLES, RolesResponse);
        }

        public static RoleService Instance()
        {
            if (instance == null)
            {
                instance = new RoleService();
            }
            return instance;
        }


        public List<ViewRole> RoleList { get; private set; }
        private Dictionary<int, ViewRole> RoleDic { get; set; }

        /// <summary>
        /// 初始化所有角色
        /// </summary>
        public void InitRoles()
        {
            GetRoles();
        }

        public void RefreshRoles()
        {
            GetRoles();
        }

        private void GetRoles()
        {
            AllRolesReq msg = new AllRolesReq(MessageId.REQUEST_ALL_ROLES);
            ApplicationClient.Instance().Send(msg);
        }

        private void RolesResponse(ResponseBaseMessage message)
        {
            if (message is AllRolesResp msg)
            {
                if (msg.Roles == null)
                {
                    return;
                }
                RoleList = msg.Roles;
                RoleDic = RoleList.ToDictionary(role => role.ID, role => role);
                RefreshRolesEvent?.Invoke(RoleList);
            }
        }

        /// <summary>
        /// 通过ID获取角色
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns>角色对象</returns>
        public ViewRole GetRoleById(int id)
        {
            if (RoleDic.ContainsKey(id))
            {
                return RoleDic[id];
            }
            return null;
        }


    }
}
